//
//  ZLPResultViewController.m
//  TangYi
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 赵连鹏. All rights reserved.
//

#import "ZLPResultViewController.h"
#import <AFNetworking.h>
#import "ZLPProductCollectionViewCell.h"
#import <UIImageView+WebCache.h>
#import "ZLPSearchResultModel.h"
#import <MJRefresh.h>
#import "ZLPResultDetailViewController.h"

@interface ZLPResultViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain) UICollectionView *collection;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, assign) NSInteger currectPage;

@end

@implementation ZLPResultViewController

- (void)dealloc {
    
    [_productArr release];
    [_collection release];
    [_str release];
    [super dealloc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"搜索结果";
    
    [self createCollectionView];
    
    [self isWlan];
    
    self.currectPage = 0;
    [self headerRefresh];
    [self footerRefresh];
    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            [self createData];
            
        } else {
            
            //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            //            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
            
        }
        
    }];
}

- (void)headerRefresh {
    
    [self.productArr removeAllObjects];
    
    self.collection.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        self.currectPage = 0;
        [self createData];
        
    }];
}

- (void)footerRefresh {
    self.collection.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       
        self.currectPage++;
        [self createRefreshData];
    }];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 2 - 15, WIDTH / 2 + 13);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:layout];
    [self.view addSubview:self.collection];
    [_collection release];
    self.collection.showsVerticalScrollIndicator = NO;
    self.collection.backgroundColor = [UIColor whiteColor];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.collection registerClass:[ZLPProductCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
}

- (void)createData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/initData?app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.1&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSDictionary *dic = responseObject;
        
        self.productArr = [NSMutableArray array];
        self.productArr = [ZLPSearchResultModel baseModelByArr:dic[@"data"][@"product"]];
        
        if (self.productArr.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"搜索失败" message:@"您搜索的物品不存在" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        [self.collection.header endRefreshing];
        [self.collection reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@", error);
        
    }];
}

- (void)createRefreshData {
    NSString *strURL = @"http://open3.bantangapp.com/base/search/list";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&category=12&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.1&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&type_id=2&v=7", [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
,self.currectPage];
    NSData *bodyDate = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyDate];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSMutableArray *tempArr = [NSMutableArray array];
        tempArr = [ZLPSearchResultModel baseModelByArr:dic[@"data"]];
        for (ZLPSearchResultModel *tempModel in tempArr) {
            [self.productArr addObject:tempModel];
        }
        
        
        [self.collection.footer endRefreshing];
        [self.collection reloadData];
        
    }];
}


#pragma mark collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.productArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZLPProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor grayColor];
    
    /*  关键字高亮  */
    ZLPSearchResultModel *model = [[ZLPSearchResultModel alloc] init];
    model = self.productArr[indexPath.row];
    
    NSString *title = model.title;
    NSMutableAttributedString *keyword = [[NSMutableAttributedString alloc] initWithString:title];
    
    NSRange keywordRange = [title rangeOfString:self.str];
    
    [keyword addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:keywordRange];
    
    [cell.titleLabel setAttributedText:keyword];
    
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@", model.price];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZLPResultDetailViewController *detailVC = [[ZLPResultDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    detailVC.numID = [self.productArr[indexPath.row] numID];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
